package com.zxh.zhenxihuan.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
public class LoginController {
    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    AuthenticationManager authenticationManager;

    @GetMapping("/test")
    @PreAuthorize("hasAuthority('zhangsan')")
    public String test(){
        return "test";
    }

    @GetMapping("/test3")
    @PreAuthorize("hasAuthority('lisi')")
    public String test3(){
        return "test3";
    }

    @GetMapping("/test2")
    @PreAuthorize("hasAuthority('zhangsan') or hasAuthority('lisi')")
    public String test2(){
        return "test2";
    }

    @PostMapping("/login2")
    public String refreshAndGetAuthenticationToken(

            @RequestBody Map<String,Object> map) throws AuthenticationException {
            String username = (String)map.get("username");
            String password = (String)map.get("password");
           /* @RequestParam String username,
            @RequestParam String password) throws AuthenticationException {*/
       /* System.out.println("新密码在这，"+(new BCryptPasswordEncoder()).encode("666666"));*/
        return generateToken(username, password);
    }

    private String generateToken(String username, String password) {
        UsernamePasswordAuthenticationToken upToken =
                new UsernamePasswordAuthenticationToken(username, password);
        // Perform the security
        final Authentication authentication =
                authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // Reload password post-security so we can generate token
        final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        // 持久化的redis
        String token = (new BCryptPasswordEncoder()).encode(username)+"-"+ UUID.randomUUID();
                redisTemplate.opsForValue().set(token,username);
        return token;
    }
}
